#ifndef CONNECTION_H
#define CONNECTION_H

#include <QHostAddress>
#include <QString>
#include <QTcpSocket>
#include <QTime>
#include <QTimer>
#include <QJsonObject>

static const int MaxBufferSize = 1024000;

class Connection : public QTcpSocket
{
    Q_OBJECT
    Q_PROPERTY(QString identity READ identity WRITE setIdentity)
public:
    enum ConnectionState {
        WaitingForGreeting,
        ReadingGreeting,
        ReadyForUse
    };
    enum DataType {
        FILE,
        Message,
        Ping,
        Pong,
        Greeting,
        Undefined
    };

    Connection(QObject *parent = 0);

public:
    QString identity() const;
    void setIdentity(const QString &identity);
    bool sendMessage(const QByteArray &message);
    bool sendFile(const QByteArray &message);
signals:
    void readyForUse();
    void newMessage(const QByteArray &message);
    void newFile(const QVariantMap &message);
protected:
    void timerEvent(QTimerEvent *timerEvent) Q_DECL_OVERRIDE;

private slots:
    void processReadyRead();
    void sendPing();
    void sendGreetingMessage();

private:
    int readHeaderIntoBuffer(int maxSize = MaxBufferSize);
    int dataLengthForCurrentData();
    bool readProtocolHeader();
    bool hasEnoughData();
    void processData();
     bool sendMessage(const QByteArray &headerText, const QByteArray &data);
private:

    QTimer pingTimer;
    QTime pongTime;
    QByteArray m_buffer;
    ConnectionState state;
    DataType currentHeaderType;
    int numBytesForCurrentData;
    int transferTimerId;
    bool isGreetingMessageSent;

    QString m_identity;
};

#endif
